<?php

/**
 * MVM_MALL 网上商店系统  淘宝数据转换
 * ============================================================================
 * 版权所有 (C) 2007-2010 www.mvmmall.com，并保留所有权利。
 * 网站地址: http://www.mvmmall.com
 * ----------------------------------------------------------------------------
 * 这是一个免费开源的软件；这意味着您可以在不用于商业目的的前提下对程序代码
 * 进行修改、使用和再发布。
 * ============================================================================
 * $Author:  www.mvmmall.com  $
 * $Date: 2008-02-28 $
 * $Id: taobao.inc.php  www.mvmmall.com$
 * ---------------------------------------------
*/

if(!defined('MVMMALL') || !defined('IN_ADMINCP')) exit('Access Denied');
if($action=='list'){
    if ($setp==1) {
    	include_once MVMMALL_ROOT.'./include/phpzip.class.php';
    	require_once MVMMALL_ROOT.'./include/category_tree.class.php';
    	$tree           = new tree();
    	$tree->arr_tree = $cache->get_cache('tree');

        //发票
        if ($mm_use_vat==2){
            $use_vat=0;
        }else {
            $use_vat=1;
        }
        $rowset = new PHPZip;
        $excel_save = "宝贝名称,宝贝类目,店铺类目,新旧程度,省,城市,出售方式,宝贝价格,加价幅度,宝贝数量,有效期,运费承担,平邮,EMS,快递,付款方式,支付宝,发票,保修,自动重发,放入仓库,橱窗推荐,发布时间,心情故事,宝贝描述,宝贝图片,宝贝属性,团购价,最小团购件数,邮费模版ID,会员打折,修改时间,上传状态,图片状态";
        $excel_save = explode(',',$excel_save);
        $excel_save = implode("\t",$excel_save) . "\n";
        
        //读取商品分类数据
        //多重分类
        $rt_cat    = false;
        $result    = $db->query("SELECT * FROM {$tablepre}goods_cat WHERE cat_id='$goods_category'");
        while ($rt = $db->fetch_array($result)) {
        	$rt_cat[$rt['goods_id']] = $rt['goods_id'];
        }
        $goods_cat   = $rt_cat ? 'OR uid IN('.implode(",", $rt_cat).')': false;
        //end
        $arr = implode(',',$tree->get_id($goods_category));
        $cat_in = $arr ? $goods_category.','.$arr: $goods_category;
        
        $search_sql  = $goods_category!=''?"WHERE goods_category IN($cat_in) $goods_cat":'';

        $result=$db->query("SELECT *  FROM `{$tablepre}goods_table` $search_sql");
        while($list = $db->fetch_array($result)) {
            $list[goods_file2] = stripslashes($list[goods_file2]);
            $list[goods_main]  = '"' . str_replace('"', '""', $list[goods_main]) . '"';
            $list[goods_name]  = strip_tags($list[goods_name]);
            $goods_value = "$list[goods_name],$baobei_id,0,5,$province,$city,b,$list[goods_sale_price],0,$list[goods_stock],14,1,$post_price,$ems_price,$express_price,2,1,$use_vat,0,1,0,0,1980-1-1 0:00:00,,$list[goods_main],$list[goods_file2], ,0,0,0,0, ,100,1";
            $goods_value = explode(',',$goods_value);
            $excel_save .= implode("\t",$goods_value) . "\n";
            //压缩图片
            if (!empty($list['goods_file2']) && is_file(ROOTPATH . $list['goods_file2'])){
                $rowset->addFile(file_get_contents(ROOTPATH . $list['goods_file2']), $list['goods_file2']);
            }
        }
        header("Content-Type: application/vnd.ms-excel;");
        $rowset->addFile("\xFF\xFE" . utf8_str($excel_save), "mvmmall_goods_taobao($goods_category).csv");
        header("Content-Disposition: attachment; filename=mvmmall_goods_taobao($goods_category).zip");
        header("Content-Type: application/unknown");
        exit($rowset->file());
    }else {
    	//分类选择
       $cat_menu   = cat_menu('goods_category',$goods_category);
       require_once template('taobao');
       footer(); 
    }
}

elseif ($action=='add') {
    if ($setp==1){
        //图片路径
        $img_dir = ROOTPATH . 'shopimg/' . date('Ym') . '/';
        if (!file_exists($img_dir)){
            make_dir($img_dir);
            make_dir($img_dir.'thumb');//缩图图片
            make_dir($img_dir.'watermark');//水印图片
        }
        $row = 1;
        $handle = fopen($_FILES[csv_file][tmp_name],"r");
        while ($csv_arr = fgetcsv($handle,1024, "\t")) {
            if ($row == 1)
            {
                $row++;
                continue;
            }
               $img_arr=explode(".", basename(str_replace("\\", "/", $csv_arr[25])));//图片名称
               $goods_file2 = 'shopimg/' . date('Ym') . '/'.$img_arr[0].$img_taobo;//图片路径
               $cost_price   = $csv_arr[7]-$goods_cost;
               $market_price = $csv_arr[7]+$goods_market_price;
               $list =$db->fetch_row($db->query("SELECT MAX(uid)+1 FROM ".$mvm_goods_table));
               $goods_id=$list[0];
               $goods_code = goods_code($goods_id);
               $rows = array(
                   member_uid            => $m_check_uid,
                   use_direct            => $use_direct,
                   goods_class           => $goods_class,
                   goods_status          => $goods_status,
                   goods_category        => $goods_category,
                   goods_mcategory1      => $goods_mcategory1,
                   goods_mcategory2      => $goods_mcategory2,
                   goods_mcategory3      => $goods_mcategory3,
                   goods_mcategory4      => $goods_mcategory4,
                   goods_rank            => $goods_rank,
                   goods_grant           => $goods_grant,
                   goods_skin            => $goods_skin,
                   goods_code            => $goods_code,
                   goods_name            => strip_tags($csv_arr[0]),
                   goods_key             => $goods_key,
                   goods_brand           => $goods_brand,
                   goods_advance         => $goods_advance,
                   goods_add_goods       => $goods_add_goods,
                   goods_check_stock     => $goods_check_stock,
                   goods_stock           => $csv_arr[9],
                   goods_cost            => $cost_price,
                   goods_market_price    => $market_price,
                   goods_sale_price      => $csv_arr[7],
                   event_price           => $event_price,
                   price_sale            => '1',
                   goods_point           => $goods_point,
                   goods_kg              => $goods_kg,
                   goods_free_delivery   => $goods_free_delivery,
                   goods_file1           => $goods_file2,
                   goods_file2           => $goods_file2,
                   goods_movie           => $goods_movie,
                   goods_addoption1      => $goods_addoption1,
                   goods_addoption2      => $goods_addoption2,
                   goods_addoption3      => $goods_addoption3,
                   goods_addoption4      => $goods_addoption4,
                   use_html              => $use_html,
                   goods_main            => $csv_arr[24],
                   goods_head            => $goods_head,
                   goods_foot            => $goods_foot,
                   goods_admin_memo      => $goods_admin_memo,
                   goods_email           => $goods_email,
                   goods_supply_id       => $goods_supply_id,
                   goods_supply_email    => $goods_supply_email,
                   goods_phone           => $goods_phone,
                   start_date            => $start_date,
                   end_date              => $end_date,
                   register_date         => $m_now_time,
                   upv                   => '1',
                   up_date               => $m_now_time,
                   goods_mony            =>$goods_mony,
                   );
               $db->insert($mvm_goods_table,$rows);
               $list = $db->get_one("SELECT goods_rank FROM $mvm_goods_table WHERE goods_rank = '$goods_rank'");
               $list[goods_rank] && $db->query("UPDATE $mvm_goods_table SET goods_rank = goods_rank + 1 WHERE goods_rank >= '$goods_rank'");
        }
        fclose($handle);
        admin_msg($lang[success]);
    }
    $mm_brand = brand_cache();
    $product[goods_rank]='1';
    $product[price_sale]='1';
    $product[goods_stock] = $mm_nums_stock;
    $product[goods_check_stock]= $mm_check_stock;
    require_once template('taobao_add');   
}

function utf8_str($str) {
    $str_len = strlen($str);
    $start_len = 0;
    $text_str = '';
    if ($str_len == 0){
        return $text_str;
    }
    while ($start_len < $str_len){
        $nums = ord($str{$start_len});
        if ($nums < 127){
            $text_str .= chr($nums) . chr($nums >> 8);
            $start_len += 1;
        }else{
            if ($nums < 192){
                $start_len ++;
            }elseif ($nums < 224){
                if ($start_len + 1 <  $str_len){
                    $nums = (ord($str{$start_len}) & 0x3f) << 6;
                    $nums += ord($str{$start_len+1}) & 0x3f;
                    $text_str .=   chr($nums & 0xff) . chr($nums >> 8) ;
                }
                $start_len += 2;
            }
            elseif ($nums < 240){
                if ($start_len + 2 <  $str_len){
                    $nums = (ord($str{$start_len}) & 0x1f) << 12;
                    $nums += (ord($str{$start_len+1}) & 0x3f) << 6;
                    $nums += ord($str{$start_len+2}) & 0x3f;
                    $text_str .=   chr($nums & 0xff) . chr($nums >> 8) ;
                }
                $start_len += 3;
            }elseif ($nums < 248){
                if ($start_len + 3 <  $str_len){
                    $nums = (ord($str{$start_len}) & 0x0f) << 18;
                    $nums += (ord($str{$start_len+1}) & 0x3f) << 12;
                    $nums += (ord($str{$start_len+2}) & 0x3f) << 6;
                    $nums += ord($str{$start_len+3}) & 0x3f;
                    $text_str .= chr($nums & 0xff) . chr($nums >> 8) . chr($nums >>16);
                }
                $start_len += 4;
            }elseif ($nums < 252){
                if ($start_len + 4 <  $str_len){
                }
                $start_len += 5;
            }else{
                if ($start_len + 5 <  $str_len){
                }
                $start_len += 6;
            }
        }

    }

    return $text_str;
}